import pygame
import sys
import random

# 初始化pygame
pygame.init()

# 游戏窗口设置
WIDTH, HEIGHT = 400, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("伏继鹏飞行")

# 颜色定义
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLACK = (0, 0, 0)

# 游戏参数
gravity = 0.25
bird_movement = 0
game_active = True
score = 0
high_score = 0
floor_x_pos = 0

# 加载游戏素材
# 加载小鸟图片 - 替换原来的蓝色圆形
try:
    # 尝试加载图片，如果失败则使用默认圆形
    bird_img = pygame.image.load('微信图片_20250613115029.png').convert_alpha()
    # 调整图片大小
    bird_img = pygame.transform.scale(bird_img, (40, 40))
    bird_radius = 20  # 用于碰撞检测的半径
except:
    # 如果图片加载失败，使用默认的蓝色圆形
    print("警告: 无法加载小鸟图片，将使用默认圆形")
    bird_img = None
    bird_radius = 20

# 初始化小鸟矩形位置
bird_rect = pygame.Rect(WIDTH // 4, HEIGHT // 2, bird_radius * 2, bird_radius * 2)

# 管道图像 - 用绿色矩形代替
pipe_width = 80
pipe_height = 500
pipe_gap = 200
pipe_list = []
SPAWNPIPE = pygame.USEREVENT
pygame.time.set_timer(SPAWNPIPE, 1200)  # 每1.2秒生成一个管道

# 地面图像 - 用棕色矩形代替
floor_height = 100
floor_rect = pygame.Rect(0, HEIGHT - floor_height, WIDTH, floor_height)

# 游戏字体
font = pygame.font.Font(None, 36)


def create_pipe():
    """创建一对管道（上管道和下管道）"""
    random_pipe_pos = random.randint(200, 400)
    bottom_pipe = pygame.Rect(WIDTH, random_pipe_pos, pipe_width, pipe_height)
    top_pipe = pygame.Rect(WIDTH, random_pipe_pos - pipe_gap - pipe_height, pipe_width, pipe_height)
    return bottom_pipe, top_pipe


def move_pipes(pipes):
    """移动所有管道"""
    for pipe in pipes:
        pipe.x -= 5
    return pipes


def draw_pipes(pipes):
    """绘制所有管道"""
    for pipe in pipes:
        if pipe.y > 0:  # 下管道
            pygame.draw.rect(screen, GREEN, pipe)
        else:  # 上管道
            pygame.draw.rect(screen, GREEN, pipe)


def check_collision(pipes):
    """检查碰撞"""
    # 检查与管道的碰撞
    for pipe in pipes:
        if bird_rect.colliderect(pipe):
            return False

    # 检查与地面的碰撞
    if bird_rect.bottom >= HEIGHT - floor_height:
        return False

    # 检查是否飞出屏幕顶部
    if bird_rect.top <= 0:
        return False

    return True


def draw_floor():
    """绘制地面"""
    pygame.draw.rect(screen, (139, 69, 19), floor_rect)


def display_score(game_state):
    """显示分数"""
    if game_state == 'main_game':
        score_surface = font.render(f'分数: {int(score)}', True, WHITE)
        score_rect = score_surface.get_rect(center=(WIDTH // 2, 50))
        screen.blit(score_surface, score_rect)
    if game_state == 'game_over':
        score_surface = font.render(f'分数: {int(score)}', True, WHITE)
        score_rect = score_surface.get_rect(center=(WIDTH // 2, 50))
        screen.blit(score_surface, score_rect)

        high_score_surface = font.render(f'最高分: {int(high_score)}', True, WHITE)
        high_score_rect = high_score_surface.get_rect(center=(WIDTH // 2, 100))
        screen.blit(high_score_surface, high_score_rect)


def update_score(score, high_score):
    """更新最高分"""
    if score > high_score:
        high_score = score
    return high_score


# 游戏主循环
clock = pygame.time.Clock()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and game_active:
                bird_movement = 0
                bird_movement -= 6
            if event.key == pygame.K_SPACE and not game_active:
                game_active = True
                pipe_list.clear()
                bird_rect.center = (WIDTH // 4, HEIGHT // 2)
                bird_movement = 0
                score = 0

        if event.type == SPAWNPIPE and game_active:
            pipe_list.extend(create_pipe())

    # 填充背景色
    screen.fill((135, 206, 235))  # 天蓝色背景

    if game_active:
        # 小鸟移动
        bird_movement += gravity
        bird_rect.centery += bird_movement

        # 绘制小鸟 - 根据是否成功加载图片选择不同的绘制方式
        if bird_img:
            screen.blit(bird_img, bird_rect)
        else:
            # 如果图片加载失败，使用默认的蓝色圆形
            pygame.draw.circle(screen, BLUE, bird_rect.center, bird_radius)

        # 移动和绘制管道
        pipe_list = move_pipes(pipe_list)
        draw_pipes(pipe_list)

        # 检查碰撞
        game_active = check_collision(pipe_list)

        # 计算分数
        for pipe in pipe_list:
            if pipe.x == bird_rect.x - 40:  # 当小鸟经过管道中间时加分
                score += 0.5

        # 显示分数
        display_score('main_game')
    else:
        # 游戏结束，更新最高分
        high_score = update_score(score, high_score)
        display_score('game_over')

        # 显示游戏结束文本
        game_over_surface = font.render('游戏结束! 按空格键重新开始', True, WHITE)
        game_over_rect = game_over_surface.get_rect(center=(WIDTH // 2, HEIGHT // 2))
        screen.blit(game_over_surface, game_over_rect)

    # 绘制地面
    draw_floor()

    # 更新屏幕
    pygame.display.update()
    clock.tick(60)  # 60帧每秒
